﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WordsGame
{
    internal class Tree
    {
        private TreeNode _root;

        public Tree()
        {
            _root = new TreeNode();
        }

        public void Add(string word)
        {
            Add(_root, word);
        }

        public bool Contains(string word)
        {
            TreeNode current = _root;
            for (int i = 0; i < word.Length; ++i)
            {
                if (!current.Descendants.ContainsKey(word[i]))
                {
                    return false;
                }

                current = current.Descendants[word[i]];
            }

            return true;
        }

        private static void Add(TreeNode node, string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                node.Descendants[TreeNode.FakeLeafe] = TreeNode.FakeNode();
            }
            else
            {
                TreeNode newNode = node.Descendants.ContainsKey(text[0]) ? 
                    node.Descendants[text[0]] : new TreeNode(text[0]);

                node.Descendants[text[0]] = newNode;
                Add(newNode, text.Length == 1 ? string.Empty : text.Substring(1));
            }
        }
    }
}
